__author__ = 'sitong'

# !_*_coding:utf-8_*_
import json
import pprint

import xlrd
from xpinyin import Pinyin

p = Pinyin()
apply_dic = []


def get_excel():
    with xlrd.open_workbook('konten.xlsx') as workbook:
        name_sheets = workbook.sheet_names()  # 获取Excel的sheet表列表，存储是sheet表名
        # print(name_sheets)
        for index in name_sheets:  # for 循环读取每一个sheet表的内容
            if index != "汇总表":
                continue
            sheet_info = workbook.sheet_by_name(index)  # 根据表名获取表中的所有内容，sheet_info也是列表，列表中的值是每个单元格里值
            first_line = sheet_info.row_values(0)  # 获取首行，我这里的首行是表头，我打算用表头作为字典的key，每一行数据对应表头的value，每一行组成一个字典
            values_merge_cell = merge_cell(sheet_info)  # 这里是调用处理合并单元格的函数
            for i in range(2, sheet_info.nrows):  # 开始为组成字典准备数据
                other_line = sheet_info.row_values(i)
                # print(other_line)
                for key in values_merge_cell.keys():
                    if key[0] == i:
                        rs = values_merge_cell[key].replace('\n', '')
                        other_line[key[1]] = rs
                # print(other_line)
                # dic = list_dic(first_line,other_line)  #调用组合字典的函数，传入key和value，字典生成
                apply_dic.append(other_line)
            return apply_dic


def list_dic(list1, list2):
    '''
    two lists merge a dict,a list as key,other list as value
    :param list1:key
    :param list2:value
    :return:dict
    '''
    dic = dict(map(lambda x, y: [x, y], list1, list2))
    return dic


def merge_cell(sheet_info):
    '''
    #handle Merge transverse cells and handle Merge Vertical Cells, assign empty cells,
    :param rlow:row, include row exclusive of row_range
    :param rhigh:row_range
    :param clow:col, include col exclusive of col_range
    :param chigh:col_range
    :param sheet_info:object of sheet
    :return:dic contain all of empty cells value
    '''
    merge = {}
    merge_cells = sheet_info.merged_cells
    for (rlow, rhigh, clow, chigh) in merge_cells:
        value_mg_cell = sheet_info.cell_value(rlow, clow)
        if rhigh - rlow == 1:
            # Merge transverse cells
            for n in range(chigh - clow - 1):
                merge[(rlow, clow + n + 1)] = value_mg_cell
        elif chigh - clow == 1:
            # Merge Vertical Cells
            for n in range(rhigh - rlow - 1):
                merge[(rlow + n + 1, clow)] = value_mg_cell
    return merge


def getRoot(line, root):
    # print('new line:',line)
    for index in range(0, len(line)):
        name = line[index]
        name= name.replace('\n', '')
        name= name.replace(' ', '')
        if name == '':
            continue
        if name in root:
            print('in root',name)
            continue
            # print(line[index],"father ",line[index-1])
        # print('nothing2', name)
        father = line[index - 1]
        if index == 0:
            father = 'root'
        node = Node(name.replace('\n', ''), father.replace('\n', ''))
        # print(root)
        root[name] = node
        # print(node.father, '->', node.label)
    return root


class Node:
    label = ""
    value = ""
    childrens = []
    children_str = ''

    def __init__(self, label, father):
        self.label = label
        self.value = p.get_pinyin(label,splitter='_')
        self.father = father
        self.childrens_obj = []
        self.children=[]

    def addChildren(self, boy):
        self.childrens_obj.append(boy)
        # children_str=''
        # for item in self.children:
        #     children_str=children_str+str(item)
        # self.children_str = children_str
    def toString(self):
        dicc= self.__dict__
        # print('in tostring',self,len(self.childrens),self.label)
        if len(self.childrens_obj)>0:
            # print(self.label, self.childrens, len(self.childrens))
            for item in self.childrens_obj:
                # print('item is:',item,len(item.childrens))
                dicc['children'].append(item.toString())
            dicc['childrens_obj']=""
        return dicc



def run():
    exs = get_excel()
    # return 0
    index = 1
    root = {}
    root2 = {}
    root3 = {}
    root4 = {}
    root2['root'] = Node("root", None)
    for item in exs:
        # print(index ," ",item)
        # root =getRoot(item,"第二段编码",root)
        root2 = getRoot(item, root2)
        # root3 = getRoot(item,"第三段编码", "第四段编码", root3)
        # root4 = getRoot(item, "第四段编码", "第五段编码", root4)

        index = index + 1
    for item in root2:
        # print('')
        # print('new node')
        node = root2[item]
        # get father
        if node.label=='建筑项目管理类':
            print(node.father, '->', node.label)
            print(node)
        if node.father!=None:
            fatherNode = root2[node.father]
            # print(fatherNode.father, '->', fatherNode.label)
            fatherNode.addChildren(node)
        # father add children

        # if node.father!=None:
        #     print(node.father,'->',node.label)
    print(root2['root'])
    # getRoot('声像与实物档案类',[])
    # ro1 = Node('行政管理','')
    # ro2 = Node('考勤','行政管理')
    # ro3 = Node('党务工作规章制度','考勤')
    # ro1.addChildren(ro2)
    # ro2.addChildren(ro3)
    #
    ro1= root2['root']
    ss=ro1.toString()
    print('ss')
    # print(ss['children'])
    file =open('tojson/json.txt',mode='w')
    json_o = str(ss['children'])
    json_o= json_o.replace('\'','"')
    file.write(json_o)
    file.close()



if __name__ == '__main__':
    run()
